<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>document</title>
  <style type="text/css">
  *{margin: 0;padding: 0;}
 
  </style>
  <script type="text/javascript">
    window.onload = function(){
      var str = '';
      var leng = 22;
      var num = 0;
      var num1 = 0;
      var timer = null;
      var timer1 = null;
      var Onoff = true;
      var Div = document.getElementsByTagName('div');
      for (var i = 0; i < leng; i++) {
        str += '<div style="width:50px;height:50px;background:red;position:absolute;top:0px;left:' +  i * 60 + 'px;"></div>';
      };
      document.body.innerHTML = str;
      function getstyle(obj, attr) {
        return obj.currentstyle ? obj.currentstyle[attr] : getComputedStyle(obj)[attr];
      }
      function Move(obj, attr, dir, target){ //
        parseInt(getstyle(obj, attr)) < target ? dir : -dir;
        clearInterval(obj.timer)
        obj.timer = setInterval(function () {
          var speed = parseInt(getstyle(obj, attr)) + dir;
          if (speed > target && dir > 0 || speed < target && dir < 0) {
            speed = target;
          }
          obj.style[attr] = speed + 'px';
          if (speed == target) {
            clearInterval(obj.timer);
          }
        }, 50)
      }
      for (var i = 0; i < Div.length; i++) {
        Div[i].index = i;
        Div[i].onclick = function(){
          num = this.index;
          num1 = this.index
          clearInterval(timer);
          clearInterval(timer1);
            timer = setInterval(function(){
              Onoff ? Move(Div[num], 'top', 20, 500) : Move(Div[num], 'top', -20, 0);
              num++;
              if (num == leng) {
                clearInterval(timer);
              }
            },100)
            timer1 = setInterval(function(){
              Onoff ? Move(Div[num1], 'top', 20, 500) : Move(Div[num1], 'top', -20, 0);
              num1--;
              if (num1 < 0) {
                clearInterval(timer1);
              }
            },100) 
            Onoff = !Onoff; 
        }
      };
    }
  </script>
</head>
<body>
</body>
</html>